<template>
  <div
    class="chart"
    :id="chartId"
    :style="{
      height: chartHeight ? chartHeight + 'px' : '100%',
      width: chartWidth
    }"
  ></div>
</template>

<script>
export default {
  name: 'Chart',
  props: {
    chartId: {
      type: String,
      required: true
    },
    chartWidth: {
      type: String
    },
    chartHeight: {
      type: Number
    },
    options: {
      type: Object,
      default: () => ({})
    }
  },
  watch: {
    options: {
      handler(options) {
        this.chart.setOption(options, true)
      },
      deep: true
    },
    chartWidth() {
      if (this.chart) {
        this.chart.resize()
      }
    },
    chartHeight() {
      if (this.chart) {
        this.chart.resize()
      }
    }
  },
  mounted() {
    this.initChart()
    // this.resizeObserver = new ResizeObserver((entries) => {
    //   if (this.chart) {
    //     this.chart.resize()
    //   }
    // })
    // this.resizeObserver.observe(
    //   document.getElementById(this.chartId)
    // )
  },
  beforeUnmount() {
    if (this.chart) {
      this.chart.dispose()
    }
    this.chart = null
    if (this.resizeObserver) {
      this.resizeObserver.unobserve()
    }
  },
  methods: {
    initChart() {
      this.chart = null

      this.chart = echarts.init(
        document.getElementById(this.chartId)
      )
      if (this.options) {
        this.chart.setOption(this.options, true)
      }
    }
  }
}
</script>

<style lang="scss" scoped></style>
